#!/usr/bin/env python
# coding: utf-8

import pandas as pd
# 1.定义DataFrame对象
data = {'color':['blue', 'green', 'yellow', 'red', 'white'],
        'object':['ball', 'pen', 'pencil', 'paper', 'mug'],
        'price' :[1.2, 1, 0.6, 0.9, 1.7]}
frame = pd.DataFrame(data)
frame
frame2 = pd.DataFrame(data, columns = ['object', 'color'])
    # columns可以自选指定列的顺序
frame2
    # 指定Index标签
frame2 = pd.DataFrame(data, index = ['ONE', 'TWO', 'THREE', 'FOUR', 'FIVE'])
frame2

    # 使用构造函数，定义DataFrame对象
import numpy as np
frame3 = pd.DataFrame(np.arange(16).reshape(4,4),
                      index = ['red', 'blue', 'yellow', 'white'],
                      columns = ['BALL', 'PEN', 'PENSIL', 'PAPER'])
frame3

# 2.Select Elements
frame.columns
frame.index
frame2.index
frame.values
              
    # Select Columns
frame['price']  # 'price'作为索引
frame.price  # DataFrame的实例属性
    # columns可以自选指定列的顺序
frame2 = pd.DataFrame(data, columns = ['object', 'color'])
frame2
frame2 = pd.DataFrame(data, index = ['ONE', 'TWO', 'THREE', 'FOUR', 'FIVE'])
frame2
    # Select Rows
frame.loc[0]  # 返回Series对象，显示第1行的所有属性，column变为index
frame.loc[[1,2,4]]  # 用一个数组指定多个索引值
frame.loc[2:]

# 3.Assignment: 赋值
    # 指定二级结构标签，便于识别
frame.index.name = 'id'
frame.columns.name = 'items'
frame
    # 添加新列
frame['new_column'] = 12
frame
frame['new_column'] = [3.0, 1.3, 2.2, 0.8, 1.1]
frame
    # 使用Series对象为DataFrame赋值
import numpy as np
ser = pd.Series(np.arange(5))
ser
frame['new_column'] = ser
frame
    # 修改单个元素，df[column][row]
frame['new_column'][2] = 15
frame
        # NOT Recommended
frame2['color']['TWO'] = 'GREY'
frame2
        # Recommend: df.loc[row, column]
        # 深度copy问题
frame2.loc['TWO', 'color'] = 'BLUE'
frame2

# 4.belong: 元素的所属关系
    # isin()
frame
frame.isin([1.0, 'pen'])
    # 传入：包含bool值的DataFrame对象，可以得到满足条件的DataFrame对象
frame[frame.isin([1,'pen'])]

# 5.Delete: 删除列
del frame['new_column']
frame

# 6.Filter: 筛选
frame['price']>0.9
frame[frame['price']>0.9]

# 7.嵌套字典生成DataFrame对象
nestdict = {
    'red':{2012:22, 2013:33},
    'blue':{2011:17, 2012:27, 2013:18},
    'white':{2011:13, 2012:22, 2013:16}
}
frame4 = pd.DataFrame(nestdict)
frame4

# 8.DataFrame转置
frame4.T